var deleteUrl = "";
let startTime = "";
let endTime = "",
    total = 0,
    type = 38,
    maximgsize = 100;
let types = [{ "id": 39, "text": "茶言说：页面以方形排版的形式，开放客户上传视频，图片，茶评，相互评论自由度高，管理负责审核通过任何评论;" },
    { "id": 40, "text": "茶精选：推文形式，介绍宜关品牌的产品，产品上加链接专去购买页面，同时开放评论以及点赞;" },
    { "id": 38, "text": "茶文化：长条形排版，精选选公众号阅读量高的文章投放茶叶相关知识，只开设评论和点赞;" },
];
layui.config({
    version: '1510164124181'
}).use(['laypage', 'laydate', 'layer', 'table', 'form', 'element', 'upload'], function() {
    table = layui.table, laypage = layui.laypage, layer = layui.layer, laydate = layui.laydate, upload = layui.upload, element = layui.element, form = layui.form;
    element.on('tab(docDemoTabBrief)', function(data) {
        type = $(this).attr("lay-id");
        typeId = $(this).data("id");
        $(".layui-elem-quote").html(types[typeId].text);
        sessionStorage.setItem("type", type);
        pageNo = 1;
        showHide();
        findRotation();
        inituserdata();
    });
    //日期时间范围
    laydate.render({
        elem: '#times',
        type: 'datetime',
        range: true,
        trigger: 'click'
    });
    //监听折叠
    element.on('collapse(test)', function(data) {
        layer.msg('展开状态：' + data.show);
    });
    let active = {
        getAddData: function() { //添加
            AddInfo("");
        },
        getCheckData: function() { //批量删除
            let checkStatus = table.checkStatus('tableInfoId'),
                data = checkStatus.data;
            let dataId = "";
            for (var i = 0; i < data.length; i++) {
                dataId += data[i].id + ",";
            }
            if (dataId.length > 0) {
                dataId = dataId.substring(0, dataId.length - 1);
                if (type == 38) {
                    deleteUrl = "delFindArticleById";
                } else if (type == 40) {
                    deleteUrl = "delFindTeatal";
                }
                DeleteAjaxHttp(dataId, deleteUrl);
            } else {
                top.layer.msg("请选择你要删除的数据!!");
            }
        }
    };

    form.on('select(selectState)', function(obj) {
        var id = $(obj.elem).attr("data-id");
        var val = obj.value;
        updateFindStateInfoById(id, val);
    });

    $('.demoTable .layui-btn').on('click', function() {
        let type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
    //监听操作
    form.on('switch(stateSelectDemo)', function(obj) {
        pageNo = 1;
        inituserdata();
    });

    //监听操作
    form.on('switch(typeSelectDemo)', function(obj) {
        pageNo = 1;
        inituserdata();
    });
    // updStateFindTeatal
    //监听搜索操作
    form.on('submit(formSubSearch)', function(obj) {
        pageNo = 1;
        inituserdata();
    });
    //监听工具条
    table.on('tool(tableInfo)', function(obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            if (type == 38) {
                deleteUrl = "delFindArticleById";
            } else if (type == 40) {
                deleteUrl = "delFindTeatal";
            }
            DeleteAjaxHttp(data.id, deleteUrl);
        } else if (obj.event === 'edit') {
            AddInfo(data.id);
        } else if (obj.event === 'detail') {
            detailInfo(data.id);
        }
    });

    //监听单元格编辑
    table.on('edit(tableInfo)', function(obj) {
        let value = obj.value //得到修改后的值
            ,
            data = obj.data //得到所在行所有键值
            ,
            field = obj.field; //得到字段
        layer.confirm("您确定将此条信息修改为:" + value + "?", { icon: 3, title: '提示信息' }, function(index) {
            index = top.layer.msg('提交中，请稍候', { icon: 16, time: false, shade: 0.8 });
            editInfo(data.id, field, value);
        });
    });
    findRotation(); //查询轮播图
    inituserdata();
    showHide();
});

function showHide() {
    if (type == 38) {
        $(".typeNot38").hide();
        $(".typeNot39_40").show();
        $(".typeNot39").show();
    } else if (type == 39) {
        $(".typeNot38").show();
        $(".typeNot39_40").hide();
        $(".typeNot39").hide();
    } else if (type == 40) {
        $(".typeNot38").show();
        $(".typeNot39").show();
        $(".typeNot39_40").hide();
    }
}

function onloadInfo() {
    inituserdata();
}

function updateFindStateInfoById(id, state) {
    $.ajax({
        type: "POST",
        url: httpurl + "/updStateFindTeatal",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: JSON.stringify({ "id": id, "state": state }),
        success: function(data) {
            top.layer.closeAll();
            top.layer.alert(data.msg);

        }
    });
}

function detailInfo(dataId) {
    var tempInfo = "?page=" + pageNo;
    if (dataId != null && dataId != "" && dataId != undefined) {
        tempInfo += "&Id=" + dataId;
    }
    sessionStorage.setItem("type", type);
    layer.open({
        type: 2,
        title: ['文章管理', 'color:red;font;font-weight: 600;'],
        area: ['100%', '100%'],
        fixed: false, //不固定
        maxmin: true,
        content: 'FindComment.html' + tempInfo
    });
}

function AddInfo(dataId) {
    var tempInfo = "?page=" + pageNo;
    if (dataId != null && dataId != "" && dataId != undefined) {
        tempInfo += "&Id=" + dataId;
    }
    sessionStorage.setItem("type", type);
    layer.open({
        type: 2,
        area: ['100%', '100%'],
        fixed: false, //不固定
        maxmin: true,
        content: 'AddFind.html' + tempInfo
    });
}
let pimg = [];
let paddress = [];

function addCarouseImg() {
    let indexs = layer.open({
        type: 1,
        title: "添加轮播图",
        area: ['700px', '300px'],
        btn: ["提交", "取消"],
        shadeClose: false, //点击遮罩关闭
        content: '<form class="am-form" style="width: 80%;margin: 0 auto;">' +
            '<div class="form-group-col-2">\n' +
            '                    <div class="form-label">选择图片：</div>\n' +
            '                    <!--                    <span class="word-aux"><i class="icon-warning-sign"></i>请上传的图片宽高比例为1:1</span>-->\n' +
            '                    <div class="form-cont">\n' +
            '                        <div class="pic_li_div" id="picimg">\n' +
            '                            <img class="width35" src="../../img/addImg.jpg"/>\n' +
            '                        </div>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '                <div class="form-group-col-2">\n' +
            '                    <div class="form-label">跳转地址：</div>\n' +
            '                    <div class="form-cont">\n' +
            '                        <input id="address" type="text" value=""  class="form-control width70 form-boxed"\n' +
            '                               placeholder="请输入跳转地址"/>\n' +
            '                    </div>\n' +
            '                </div>' +
            '</form>',
        yes: function(index, layero) {
            let picimg = $("#picimg img").attr("name");
            let address = $("#address").val();
            pimg.push(picimg);
            paddress.push(address);
            $.ajax({
                type: "POST",
                url: httpurl + "/updateTypeList",
                cache: false,
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Methods": "*",
                    "Access-Control-Allow-Headers": "Authorization",
                    "Authorization": GetTokenInfo()
                },
                contentType: 'application/json',
                data: JSON.stringify({
                    "id": type,
                    "pimg": pimg.join(","),
                    "tddress": paddress.join(","),
                }),
                success: function(data) {
                    layer.close(indexs);
                    layer.alert(data.msg);
                    if (data.rtnCode == 200) {
                        findRotation(); //查询轮播图
                    }
                }
            });
        }
    });
    //上传图片
    var totalArray = new Array();
    var uploadInsts = upload.render({
        elem: '#picimg' //绑定元素
            ,
        url: httpurl + '/uploadImgQiniu?pathName=carouse&&divisor=0&dividend=1' //上传接口
            ,
        accept: 'images' // 允许上传的文件类型
            // , acceptMime: 'image/jpg,image/png'   // (只支持jpg和png格式，多个用逗号隔开),
            ,
        size: 5120 // 最大允许上传的文件大小  单位 KB
            //, auto: false //选择文件后不自动上传
            //, bindAction: '#startUpload' //指向一个按钮触发上传
            ,
        multiple: true // 开启多文件上传
            ,
        number: maximgsize //  同时上传文件的最大个数
            ,
        choose: function(obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            var arr = Object.keys(files);
            totalArray = totalArray.concat(arr);
            // 检查上传文件的个数
            if (totalArray.length > maximgsize) {
                // 超出上传最大文件
                layer.msg("上传文件最大不超过" + maximgsize + "个")
            }
        },
        done: function(res, index, upload) {
            // console.log("res", res);
            if (res.rtnCode == 200) { //上传成功
                var nameurl = res.msg;
                $("#picimg img").attr("src", visitimgurl + "/" + nameurl);
                $("#picimg img").attr("name", visitimgurl + "/" + nameurl);
            }
            this.error(index, upload);
        },
        error: function() {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn  demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function() {
                uploadInsts.upload();
            });
        }
    });
}

function SearchInfo() {
    pageNo = 1;
    inituserdata();
}

function findRotation() {
    $.ajax({
        url: httpurl + "/findRotation",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: {
            "type": type
        },
        success: function(data) {
            let dataInfo = [];
            let info = "";
            pimg = [];
            paddress = [];
            if (data.rtnCode == 200) {
                dataInfo = data.data;
            }
            for (let i = 0; i < dataInfo.length; i++) {
                if (isNotNull(dataInfo[0].imageName) && isNotNull(dataInfo[0].address)) {
                    pimg.push(dataInfo[i].imageName);
                    paddress.push(dataInfo[i].address);
                    info += '<li class="width10 carouse_li_div" style="display: inline-block;">' +
                        '<div class="pic_btn" data-index="' + i + '" onclick="delCarouseInfo(this)"><img src="../../img/close4.png" style="width: 16px;height: 16px;"></div>' +
                        '<div class="layui-anim" data-anim="layui-anim-up">' +
                        '<img src="' + dataInfo[i].imageName + '" name="' + dataInfo[i].imageName + '"/>' +
                        '</div>' +
                        '<div class="code">' +
                        '<input value="' + dataInfo[i].address + '"/>' +
                        '</div>' +
                        '</li>';
                }
            }
            $(".site-doc-anim").html(info);
        }
    });
}

function delCarouseInfo(obj) {
    layer.confirm("您确定要删除此轮播图,删除后不可恢复哟?", { icon: 3, title: '提示信息' }, function(index) {
        let indexId = $(obj).data("index");
        $.ajax({
            url: httpurl + "/delCarouseByIndex",
            cache: false,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "*",
                "Access-Control-Allow-Headers": "Authorization",
                "Authorization": GetTokenInfo()
            },
            contentType: 'application/json',
            data: {
                "type": type,
                "index": indexId
            },
            success: function(data) {
                layer.close(index);
                layer.alert(data.msg);
                if (data.rtnCode == 200) {
                    findRotation();
                }
            }
        });
    });


}

function inituserdata() {
    let state = $("#disable option:selected").val();
    let title = $("#title").val();
    let times = $("#times").val();
    let data = {};
    data["page"] = pageNo;
    data["pageSize"] = pageSize;
    data["type"] = type;
    if (type == 38) { //茶文化  无状态
        data["state"] = -1;
    } else {
        data["state"] = state;
    }
    if (isNotNull(times)) {
        data["starttime"] = times.split(" - ")[0];
        data["endtime"] = times.split(" - ")[1];
    }
    if (isNotNull(title)) {
        data["titleORContextm"] = title;
    }
    $.ajax({
        url: httpurl + "/callFindArticleLikeANDTitleANDDate",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: data,
        success: function(data) {
            let dataInfo = [];
            if (data.rtnCode == 200) {
                dataInfo = data.data.list;
                total = data.data.all;
            } else {
                total = 0;
            }
            if (type == 38) { //茶文化
                table.render({
                    elem: '#tableInfo',
                    data: dataInfo,
                    id: "tableInfoId",
                    cols: [
                        [
                            { type: 'checkbox' }, { field: 'id', align: "center", width: 80, title: 'ID', sort: true }, {
                                field: 'images',
                                align: "center",
                                title: '主图',
                                templet: function(res) {
                                    if (!isNotNull(res.images)) {
                                        return "";
                                    } else {
                                        if (res.images.indexOf(",") > -1) {
                                            return '<img class="width100" src="' + res.images.split(",")[0] + '"/>';
                                        } else {
                                            return '<img class="width100"  src="' + res.images + '"/>';
                                        }
                                    }
                                }
                            }, { field: 'createdate', align: "center", title: '发表日期', sort: true }, { field: 'title', title: '标题' }, { field: 'del', align: "center", width: 200, title: '操作', templet: '#barDemo', unresize: true }
                        ]
                    ],
                    done: function(res, curr, count) {
                        layui.each($('select'), function(index, item) {
                            var elem = $(item);
                            elem.val(elem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
                        });
                        form.render();
                    }
                });
            } else if (type == 39) { //茶言说
                table.render({
                    elem: '#tableInfo',
                    data: dataInfo,
                    id: "tableInfoId",
                    cols: [
                        [
                            { type: 'checkbox' }, { field: 'id', align: "center", width: 80, title: 'ID', sort: true }, {
                                field: 'image',
                                align: "center",
                                width: 150,
                                title: '主图',
                                templet: function(res) {
                                    if (!isNotNull(res.image)) {
                                        return "";
                                    } else {
                                        if (res.image.indexOf(",") > -1) {
                                            return '<img class="width100"  src="' + res.image.split(",")[0] + '"/>';
                                        } else {
                                            return '<img class="width100"  src="' + res.image + '"/>';
                                        }
                                    }
                                }
                            }, {
                                field: 'video',
                                align: "center",
                                width: 150,
                                title: '视频',
                                templet: function(res) {
                                    if (!isNotNull(res.video)) {
                                        return "";
                                    } else {
                                        if (res.video.indexOf(",") > -1) {
                                            return '<video class="width100"  src="' + res.video.split(",")[0] + '" controls="controls"></video>';
                                        } else {
                                            return '<video class="width100"  src="' + res.video + '" controls="controls"></video>';
                                        }
                                    }
                                }
                            }, {
                                field: 'disable',
                                align: "center",
                                title: '状态',
                                templet: '#selectState',
                                sort: true
                            }, { field: 'createdate', align: "center", title: '发表日期', sort: true }, { field: 'context', title: '内容' }, { field: 'del', align: "center", width: 200, title: '操作', templet: '#barDemo39', unresize: true }
                        ]
                    ],
                    done: function(res, curr, count) {
                        layui.each($('select'), function(index, item) {
                            var elem = $(item);
                            elem.val(elem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
                        });
                        form.render();
                    }
                });
            } else if (type == 40) {
                table.render({
                    elem: '#tableInfo',
                    data: dataInfo,
                    id: "tableInfoId",
                    cols: [
                        [
                            { type: 'checkbox' }, { field: 'id', align: "center", width: 80, title: 'ID', sort: true }, {
                                field: 'image',
                                align: "center",
                                title: '主图',
                                templet: function(res) {
                                    if (!isNotNull(res.image)) {
                                        return "";
                                    } else {
                                        if (res.image.indexOf(",") > -1) {
                                            return '<img class="width100"  src="' + res.image.split(",")[0] + '"/>';
                                        } else {
                                            return '<img class="width100"  src="' + res.image + '"/>';
                                        }
                                    }
                                }
                            }, {
                                field: 'video',
                                align: "center",
                                title: '视频',
                                templet: function(res) {
                                    if (!isNotNull(res.video)) {
                                        return "";
                                    } else {
                                        if (res.video.indexOf(",") > -1) {
                                            return '<video class="width100"  src="' + res.video.split(",")[0] + '" controls="controls"></video>';
                                        } else {
                                            return '<video class="width100"  src="' + res.video + '" controls="controls"></video>';
                                        }
                                    }
                                }
                            }, {
                                field: 'disable',
                                align: "center",
                                title: '状态',
                                templet: '#selectState',
                                sort: true
                            }, { field: 'createdate', align: "center", title: '发表日期', sort: true }
                            // , {field: 'context',title: '内容' ,templet:function(res){
                            //     return '<div style="overflow: hidden;\n' +
                            //         'text-overflow:ellipsis;\n' +
                            //         'white-space: nowrap;-webkit-line-clamp: 3;">'+res.context+'</div>';
                            // }}
                            , { field: 'del', align: "center", width: 200, title: '操作', templet: '#barDemo', unresize: true }
                        ]
                    ],
                    done: function(res, curr, count) {
                        layui.each($('select'), function(index, item) {
                            var elem = $(item);
                            elem.val(elem.data('value')).parents('div.layui-table-cell').css('overflow', 'visible');
                        });
                        form.render();
                    }
                });
            }

            top.layer.closeAll();
            page();
        }
    });
}

// function editInfo(id, field, value) {
//     var data = {};
//     data["id"] = id;
//     data[field] = value;
//     data["username"] = username;
//     $.ajax({
//         type: "POST",
//         url: httpurl + "/updateManyFindInfoById",
//         cache: false,
//         headers: {
//             "Access-Control-Allow-Origin": "*",
//             "Access-Control-Allow-Methods": "*",
//             "Access-Control-Allow-Headers": "Authorization",
//             "Authorization": GetTokenInfo()
//         },
//         contentType : 'application/json',
//         data: data,
//         success: function (data) {
//             top.layer.closeAll();
//             top.layer.alert(data.msg);
//
//         }
//     });
// }

function addInfo(id) {
    $.ajax({
        url: httpurl + "/selectPevaluateSettingById",
        cache: false,
        headers: {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "*",
            "Access-Control-Allow-Headers": "Authorization",
            "Authorization": GetTokenInfo()
        },
        contentType: 'application/json',
        data: { "id": id },
        success: function(data) {
            if (data.rtnCode == 200) {
                addInfos(data.data);
            } else {
                top.layer.alert("未找到任何数据,请刷新后再试!!");
            }
        }
    });
}


//分页
function page() {
    laypage.render({
        elem: 'page' //注意，这里的  是 ID,不用加 # 号
            ,
        count: total //数据总数，从服务端得到
            ,
        layout: ['count', 'prev', 'page', 'next', 'refresh', 'skip'],
        curr: pageNo //获取hash值为fenye的当前页
            ,
        hash: 'fenye' //自定义hash值
            ,
        limit: pageSize,
        jump: function(obj, first) {
            //首次不执行
            if (!first) {
                pageNo = obj.curr; // 当前页数;
                pageSize = obj.limit; // 当前页面记录数
                inituserdata();
            }
        }
    });
}